/**
 * 间距相关CSS规则模块
 * @version 1.0.0
 */

import { utils } from '../../../utils/utils.js';

// 处理间距相关的CSS规则
export function processSpacingRules(className, options = {}) {
    const { platform = 'H5', h5Unit = 'rem', remBase = 16 } = options;
    
    // 内外边距
    const spacingMatch = className.match(/^(m|p|mx|my|px|py|mt|mr|mb|ml|pt|pr|pb|pl)-(.+)$/);
    if (spacingMatch) {
        const [, prop, value] = spacingMatch;
        const propertyMap = {
            'm': ['margin'],
            'p': ['padding'],
            'mx': ['margin-left', 'margin-right'],
            'my': ['margin-top', 'margin-bottom'],
            'px': ['padding-left', 'padding-right'],
            'py': ['padding-top', 'padding-bottom'],
            'mt': ['margin-top'],
            'mr': ['margin-right'],
            'mb': ['margin-bottom'],
            'ml': ['margin-left'],
            'pt': ['padding-top'],
            'pr': ['padding-right'],
            'pb': ['padding-bottom'],
            'pl': ['padding-left']
        };
        
        const properties = propertyMap[prop];
        if (properties) {
            const styles = {};
            let cssValue;
            
            // 处理带单位的值
            const unitMatch = value.match(/^(\d+(?:\.\d+)?)(rpx|px|rem|em|vh|vw|vmin|vmax|%|pt|pc|in|mm|cm)$/);
            if (unitMatch) {
                const [, numValue, unit] = unitMatch;
                
                // uni-app x 只支持 number|pixel|percent|auto
                if (platform === 'APP-PLUS' || platform === 'APP-ANDROID' || platform === 'APP-IOS') {
                    if (unit === 'rem') {
                        cssValue = `${numValue * remBase}px`;
                    } else if (unit === 'em') {
                        cssValue = `${numValue * 16}px`;
                    } else if (unit === 'vw' || unit === 'vh' || unit === 'vmin' || unit === 'vmax') {
                        // 视口单位转换为px（粗略转换）
                        cssValue = `${numValue * 3.75}px`;
                    } else if (unit === '%') {
                        cssValue = `${numValue}%`;
                    } else if (unit === 'rpx') {
                        cssValue = `${numValue}rpx`;
                    } else if (unit === 'px') {
                        cssValue = `${numValue}px`;
                    } else {
                        // 其他单位转换为px
                        cssValue = `${numValue * 16}px`;
                    }
                } else {
                    cssValue = `${numValue}${unit}`;
                }
            }
            // 处理auto值
            else if (value === 'auto') {
                cssValue = 'auto';
            }
            // 处理纯数字值
            else {
                cssValue = utils.convertUnit(value, platform, { h5Unit, remBase, unitType: 'spacing' });
            }
            
            properties.forEach(property => {
                styles[property] = cssValue;
            });
            return styles;
        }
    }
    
    return null;
} 